"""
给出必要信息，自动填报健康每日报
参考：知乎用户zyh的贴：https://zhuanlan.zhihu.com/p/349123202
"""
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException, NoSuchFrameException
from selenium.webdriver.common.action_chains import ActionChains
import time


def auto_report(id, password, title, temperature, covid_test, covid_result, covid_test_time, isolation, code_color,
                short_wait_time=1, long_wait_time=3):
    chromedriver = r'chromedriver.exe'
    browser = webdriver.Chrome(chromedriver)
    url = "http://jkrb.xjtu.edu.cn/EIP/user/index.htm"
    browser.get(url)
    time.sleep(short_wait_time)
    # 使用用户信息登录
    browser.find_element(By.NAME, "username").send_keys(id)
    browser.find_element(By.NAME, "pwd").send_keys(password)
    browser.find_element(By.ID, "account_login").click()
    time.sleep(short_wait_time)
    # 点击 title
    try:
        browser.switch_to.frame(0)
    except NoSuchFrameException:
        raise ValueError("登陆失败！请检查账号和密码！")
    browser.switch_to.frame(1)
    browser.find_element(By.CSS_SELECTOR, "div[title='" + title + "'").click()
    # 点击 健康每日报
    browser.switch_to.default_content()
    browser.switch_to.frame(browser.find_element(By.XPATH, "//iframe[contains(@onload,'__iframe_onload3()')]"))
    browser.find_element(By.CSS_SELECTOR, "span[title='每日健康填报'").click()
    time.sleep(long_wait_time)
    # 点击 我已阅知
    browser.switch_to.default_content()
    browser.switch_to.frame(2)
    try:
        browser.switch_to.frame(0)
    except NoSuchFrameException:
        raise ValueError("今日已提交，请勿重复发起！")
    browser.find_element(By.ID, "mini-2$ck$0").click()
    # 填写检测时间
    if covid_test_time is not None:
        browser.find_element(By.ID, "ZJYCHSJCSJ$text").clear()
        try:
            browser.find_element(By.ID, "ZJYCHSJCSJ$text").send_keys(covid_test_time)
        except UnexpectedAlertPresentException:
            content = f"输入时间为{covid_test_time}。\n请注意核酸检测时间的格式必须为：2022-01-07 09:11，且必须是近2天（包含今天）的检测时间。"
            print(content)
            raise ValueError(content)
    # 填写体温
    browser.find_element(By.ID, "BRTW$text").clear()
    browser.find_element(By.ID, "BRTW$text").send_keys(str(temperature))
    # 是否做过48小时核酸
    if not covid_test:
        browser.find_element(By.ID, "mini-5$ck$1").click()  # 否
    else:
        browser.find_element(By.ID, "mini-5$ck$0").click()  # 是
    # 核酸结果
    browser.find_element(By.ID, "mini-10$ck$" + str(covid_result)).click()
    # 隔离情况
    browser.find_element(By.ID, "mini-11$ck$" + str(isolation)).click()
    # 一码通颜色
    browser.find_element(By.ID, "mini-12$ck$" + str(code_color)).click()
    # 提交
    browser.switch_to.parent_frame()
    browser.find_element(By.ID, "sendBtn").click()
    # 确认
    browser.find_element(By.XPATH, "//div[2]/a/span").click()
    time.sleep(2)
